﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Linq;
using System.Text.RegularExpressions;
using BlueMarineWindowsFormsClient.InternalServiceReference;
using BlueMarineWindowsFormsClient.DO;


namespace BlueMarineWindowsFormsClient
{
    public partial class frmBookingManagement : Form
    {
        private readonly InternalServiceClient _BookingManagement;
        private int _custIDSelected = -1;
        private RoomType _rt;

        public frmBookingManagement()
        {
            InitializeComponent();
            _BookingManagement = new InternalServiceClient("nettcp");
            dtpFrom.MinDate = DateTime.Now;
            dtpTo.MinDate = dtpFrom.Value.Add(new TimeSpan(1, 0, 0, 0));
        }

        private void frmBookingManagement_Load(object sender, EventArgs e)
        {
            ListCustomer();
            cmbRoomTypeList();
            var buttonColumn = new DataGridViewButtonColumn
                                   {
                                       HeaderText = "Action",
                                       Name = "SelectedRoom",
                                       Text = "+",
                                       UseColumnTextForButtonValue = true
                                   };
            gvRoom.Columns.Add(buttonColumn);
            gvRoom.CellClick += gvRoom_CellClick;
        }

        private void btnRemoveRoom_Click(object sender, EventArgs e)
        {
            lstRoomSelected.Items.Remove(lstRoomSelected.SelectedItem);
        }

        private void btnBooking_Click(object sender, EventArgs e)
        {
            try
            {
                var lstRoomID = new List<int>();
                if (_custIDSelected >0)
                {
                    for (var i = 0; i < lstRoomSelected.Items.Count; i++)
                    {
                        lstRoomID.Add(int.Parse(lstRoomSelected.Items[i].ToString()));
                    }

                    string result = _BookingManagement.BookAdd(_custIDSelected, lstRoomID, dtpFrom.Value, dtpTo.Value);
                    lblStatus.Text = result;
                }
                else
                    lblStatus.Text = "WARNING: You have to chose a Customer!";
            }
            catch (Exception ex)
            {
                lblStatus.Text = "ERROR: " + ex.Message;
            }
        }

        #region "Customer Management"        

        private void gvCust_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;
            _custIDSelected = Int32.Parse(gvCust.Rows[e.RowIndex].Cells["CustomerID"].Value.ToString());
            txtIdenfify.Text = _custIDSelected.ToString();
            txtName.Text = gvCust.Rows[e.RowIndex].Cells["CustomerName"].Value.ToString();
            var gender = Convert.ToBoolean(gvCust.Rows[e.RowIndex].Cells["CustomerSex"].Value);
            rbtnMale.Checked = gender;
            txtPhone.Text = gvCust.Rows[e.RowIndex].Cells["CustomerPhone"].Value.ToString();
            txtEmail.Text = gvCust.Rows[e.RowIndex].Cells["CustomerEmail"].Value.ToString();
            txtUN.Text = gvCust.Rows[e.RowIndex].Cells["CustomerAccount"].Value.ToString();
        }

        private void btnCreate_Click(object sender, EventArgs e)
        {
            try
            {
                string accountName = "";
                string result = _BookingManagement.CusAdd(out accountName, txtIdenfify.Text.Trim(), txtName.Text.Trim(), txtPhone.Text.Trim(), txtEmail.Text.Trim(),
                                              rbtnMale.Checked);
                if (result == "SUCCESS")
                {                    
                    ListCustomer();
                    txtUN.Text = accountName;
                    lblStatus.Text = "SUCCESS: Create a Customer Successful!";
                }
                else
                    lblStatus.Text = result;                
            }
            catch (Exception ex)
            {
                lblStatus.Text = "ERROR: " + ex.Message;
            }
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {                
                string result =  _BookingManagement.CusModify(_custIDSelected,txtIdenfify.Text, txtName.Text, txtPhone.Text, txtEmail.Text.Trim(),
                                                 rbtnMale.Checked);
                if (result == "SUCCESS")
                {
                    ListCustomer();
                    lblStatus.Text = "SUCCESS: Update a Customer Successful!";
                }
                else
                    lblStatus.Text = result;
            }
            catch (Exception ex)
            {
                lblStatus.Text = "ERROR: " + ex.Message;
            }
        }

        private void btnShow_Click(object sender, EventArgs e)
        {
            ListCustomer();
        }

        private void btnSearchCustomer_Click(object sender, EventArgs e)
        {
            List<Customer> lstCust = null;
            string SearchName = txtSearchName.Text.Trim();
            string SearchInd = txtSearchIN.Text.Trim();
            string SearchUN = txtSearchAcc.Text.Trim();

            if (SearchName != "")
                lstCust = _BookingManagement.FindCustomerByName(SearchName);
            else if (SearchInd != "")
                lstCust = _BookingManagement.FindCustomerByName(SearchInd);
            else if (SearchUN != "")
                lstCust = _BookingManagement.FindCustomerByName(SearchUN);

            gvCust.DataSource = lstCust;
        }

        private void txtPhone_Leave(object sender, EventArgs e)
        {
            string strPhone = txtPhone.Text;
            var rePhone = new Regex(@"0+\d{2,3}-\d{3}-\d{4}");
            if (rePhone.IsMatch(strPhone))
            {
                errorProvider.SetError(txtPhone, "");
                return;
            }
            errorProvider.SetError(txtPhone, "Phone number mus be valid format. \n" + "0xx[x]-xxx-xxxx");
        }

        private void txtEmail_Leave(object sender, EventArgs e)
        {
            int idxA = txtEmail.Text.IndexOf("@", StringComparison.Ordinal);
            if (idxA > -1)
            {
                if (txtEmail.Text.IndexOf(".", idxA, StringComparison.Ordinal) > idxA)
                {
                    if (_BookingManagement.CusEmailCheck(txtEmail.Text))
                    {
                        errorProvider.SetError(txtEmail, "");
                        return;
                    }
                }
            }
            errorProvider.SetError(txtEmail, "e-mail address must be valid e-mail address format.\nFor example 'someone@example.com' ");
        } 

        private void btnChoseCustomer_Click(object sender, EventArgs e)
        {
            if (_custIDSelected < 0)
                lblStatus.Text = "FAILD: You have to chose a customer!";
            else
            {
                tabControl1.SelectedTab = tabPage2;
                lblCustNameSelected.Text = "Customer Name: " + txtName.Text;
                lblCustIDSelected.Text = "Customer ID: "+ txtIdenfify.Text;
            }
        }

        // Methods
        public void ListCustomer()
        {
            List<Customer> lstCust = _BookingManagement.CusReadAll();
            if (lstCust.Count != 0)
            {
                var bs = new BindingSource {DataSource = lstCust};
                gvCust.DataSource = bs;
                lblStatus.Text = "Status: Completed!";
            }
            else
                lblStatus.Text = "ERROR: Can not connect to database!";
        }               

        #endregion

        #region "ROOM Management"        

       private void btnSearchRoom_Click(object sender, EventArgs e)
        {
            try
            {
                //List<vRoomInfo> listRoom = _BookingManagement.SearchRoom(chbxEnsure.Checked,_rt.RoomTypeID, dtpFrom.Value, dtpTo.Value,0,0,false,false,false);
                //gvRoom.DataSource = listRoom;
            }
            catch (Exception ex)
            {
                lblStatus.Text = "ERROR: " + ex.Message;
            }
        }

        private void cmbRoomTypeList()
        {
            try
            {
                List<RoomType> listRoomType = _BookingManagement.RoTyGet();
                cmbRoomType.DataSource = listRoomType;
                cmbRoomType.DisplayMember = "RoomTypeTitle";
                cmbRoomType.ValueMember = "RoomTypeID";
            }
            catch (Exception ex)
            {
                lblStatus.Text = "ERROR: " + ex.Message;
            }
        }

        private void cmbRoomType_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                _rt = (RoomType) cmbRoomType.SelectedItem;
                //txtRoomTypeInfo.Text = "Room Type Tile : " + _rt.RoomTypeTitle + "Room Rank: " + _rt.RoomRank +
                //                       "Room Price:" + _rt.RoomPrice + "Balcony: " + _rt.Balcony.ToString() + " Bath: " +
                //                       _rt.Bath.ToString() + " View: " + _rt.View.ToString();
            }
            catch (Exception ex)
            {
                lblStatus.Text = "ERROR: " + ex.Message;
            }
        }

        private void gvRoom_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            var dataGridViewColumn = gvRoom.Columns["SelectedRoom"];
            if (dataGridViewColumn != null && e.ColumnIndex == dataGridViewColumn.Index)
            {
                if (gvRoom.CurrentRow != null && e.RowIndex == gvRoom.CurrentRow.Index)
                {
                    int roomIDselected = int.Parse(gvRoom.Rows[gvRoom.CurrentRow.Index].Cells["RoomID"].Value.ToString());
                    lstRoomSelected.Items.Remove(roomIDselected);
                    lstRoomSelected.Items.Add(roomIDselected);
                }
            }
        }

        private void gvRoom_CellClick(object sender, EventArgs e)
        {
        }

        #endregion        

        private void dtpFrom_ValueChanged(object sender, EventArgs e)
        {
            dtpTo.MinDate = dtpFrom.Value.Add(new TimeSpan(1, 0, 0, 0));
        }                       
    }
}